import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { asyncRoutes } from '@/router'
// 前置守卫
const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start() // 开启进度条
  const token = store.getters.token
  // 有token
  if (token) {
    if (to.path === '/login') {
      // 一旦拦截处理，路由的后置导航守卫不会执行
      NProgress.done() // 手动关闭进度条
      next('/') // 跳转主页1
    } else {
      // 判断是否取过资料
      if (!store.getters.userId) {
        const { roles: { menus, points }} = await store.dispatch('user/getUserInfo')
        // menus -> 页面访问权限
        // points ->页面按钮操作权限
        console.log('页面操作权', points)
        console.log('页面访问权', menus)
        // console.log(asyncRoutes)
        const filterRoutes = asyncRoutes.filter(item => {
          // if (menus.includes(item.name)) {
          //   return true
          // } else {
          //   return false
          // }
          return menus.includes(item.name)
        })
        console.log(filterRoutes)
        store.commit('user/setRoutes', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      }
      next()
    }
  } else {
    // 没有token
    if (whiteList.includes(to.path)) {
      // 表示在白名单里面
      next()
    } else {
      NProgress.done() // 是为了解决手动输入地址时 进度条不关闭的问题
      next('/login')
    }
  }
})

// 路由后置导航守卫 - 进度条关闭
router.afterEach(() => {
  // 关闭进度条
  NProgress.done()
})
